import time
import psutil
import random
import paho.mqtt.client as mqtt

broker = '192.168.3.92'
port = 1883
topic = "homeassistant/sensor/"


# 获取 CPU 温度
def get_cpu_temperature():
    try:
        temperatures = psutil.sensors_temperatures()
#       print(temperatures)
        if 'coretemp' in temperatures:
            for entry in temperatures['coretemp']:
                if entry.label == 'Package id 0':
                    return entry.current

    except Exception as e:
        print(f"Error getting CPU temperature: {e}")

    return None


# 获取 CPU 占用
def get_cpu_usage():
    return psutil.cpu_percent(interval=1)

# Message Publish
def on_publish(client, userdata, mid, reason_code, properties):
    # reason_code and properties will only be present in MQTTv5. It's always unset in MQTTv3
    try:
        userdata.remove(mid)
    except KeyError:
        print("on_publish() is called with a mid not present in unacked_publish")
        print("This is due to an unavoidable race-condition:")
        print("* publish() return the mid of the message sent.")
        print("* mid from publish() is added to unacked_publish by the main thread")
        print("* on_publish() is called by the loop_start thread")
        print("While unlikely (because on_publish() will be called after a network round-trip),")
        print(" this is a race-condition that COULD happen")
        print("")
        print("The best solution to avoid race-condition is using the msg_info from publish()")
        print("We could also try using a list of acknowledged mid rather than removing from pending list,")
        print("but remember that mid could be re-used !")


# Loop Function
def loop():
    cpu_temp = get_cpu_temperature()
    cpu_usage = get_cpu_usage()
    print("CPU 温度:", cpu_temp, "°C")
    print("CPU 占用:", cpu_usage, "%")
    
    unacked_publish = set()
    mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
    mqttc.on_publish = on_publish
    mqttc.username_pw_set('ralf', password='xxxx')
    mqttc.user_data_set(unacked_publish)
    mqttc.connect(broker)
    mqttc.loop_start()

    # Our application produce some messages
    msg_info1 = mqttc.publish(topic + "cpu_temperature", cpu_temp, qos=1)
    unacked_publish.add(msg_info1.mid)

    msg_info2 = mqttc.publish(topic + "cpu_usage", cpu_usage, qos=1)
    unacked_publish.add(msg_info2.mid)

    # Wait for all message to be published
    while len(unacked_publish):
        time.sleep(0.1)

    # Due to race-condition described above, the following way to wait for all publish is safer
    msg_info1.wait_for_publish()
    msg_info2.wait_for_publish()

    mqttc.disconnect()
    mqttc.loop_stop()

# main
if __name__ == "__main__":
    while 1:
        loop()
        time.sleep(60)
